package com.wmlive.hhvideo.heihei.mainhome.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.baidu.aiupdatesdk.AIUpdateSDK;
import com.baidu.aiupdatesdk.CheckUpdateCallback;
import com.dyuiapi.api.DyUIAPI;
import com.mob.MobSDK;
import com.wmlive.hhvideo.application.AppStatusManager;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.common.base.BaseCompatActivity;
import com.wmlive.hhvideo.common.base.DcBaseActivity;
import com.wmlive.hhvideo.common.navigator.Navigator;
import com.wmlive.hhvideo.dcijkplayerlib.DcIjkPlayerManager;
import com.wmlive.hhvideo.heihei.beans.main.UpdateInfo;
import com.wmlive.hhvideo.heihei.dialog.BaiduUpdateDialog;
import com.wmlive.hhvideo.heihei.discovery.DiscoveryUtil;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.mainhome.adapter.MainNewViewPagerAdapter;
import com.wmlive.hhvideo.heihei.mainhome.fragment.HomeFragment;
import com.wmlive.hhvideo.heihei.mainhome.fragment.InfoFragment;
import com.wmlive.hhvideo.heihei.mainhome.presenter.MainNewPresenter;
import com.wmlive.hhvideo.heihei.mainhome.presenter.UserInfoCallback;
import com.wmlive.hhvideo.heihei.personal.activity.FansActivity;
import com.wmlive.hhvideo.heihei.personal.activity.FocusActivity;
import com.wmlive.hhvideo.heihei.personal.activity.PersonalHomeActivity;
import com.wmlive.hhvideo.heihei.recordvideo.DyUIAPIManager;
import com.wmlive.hhvideo.heihei.splash.SplashActivity;
import com.wmlive.hhvideo.heihei.websocket.WebSocketServiceManager;
import com.wmlive.hhvideo.jpush.IJpushBindUserView;
import com.wmlive.hhvideo.jpush.JpushBindUserPresenter;
import com.wmlive.hhvideo.jpush.JpushReceiver;
import com.wmlive.hhvideo.service.DCService;
import com.wmlive.hhvideo.utils.DeviceUtils;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.preferences.SPUtils;
import com.wmlive.hhvideo.utils.update.UpdateUtils;
import com.wmlive.hhvideo.widget.UnScrollViewPager;
import com.wmlive.hhvideo.widget.dialog.BaseDialog;
import com.wmlive.hhvideo.widget.dialog.MyDialog;
import com.wmlive.hhvideo.widget.dialog.MyDialogClickListener;
import com.wmlive.hhvideo.widget.dialog.UpDateDialog;
import com.wmlive.networklib.util.NetUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.wmlive.hhvideo.R;
import cn.wmlive.hhvideo.rxbuslib.RxBus2;
import cn.wmlive.hhvideo.rxbuslib.RxBusSubscribe;
import cn.wmlive.hhvideo.rxbuslib.ThreadMode;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 首页Activity
 */
public class MainNewActivity extends BaseCompatActivity<MainNewPresenter> implements
        ViewPager.OnPageChangeListener,
        MainNewPresenter.IMainNewView, UserInfoCallback, IJpushBindUserView {

    @BindView(R.id.vpContainer)
    public UnScrollViewPager vpContainer;
    private MainNewViewPagerAdapter pagerAdapter;
    private long exitTime = 0;
    private List<Fragment> fragmentList;
    public static int updateApkStatus = -1;//（-1: 默认状态      0：下载中       1：下载完成       2：任务被取消）
    public static int currentPage = 0;//当前ViewPager页面
    String[] permissionParams = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION};
    private UpDateDialog mUpDateDialog;
    private HomeFragment homeFragment;
    private InfoFragment infoFragment;
    private MyDialog useMobileDialog;

    private JpushBindUserPresenter jpushBindUserPresenter;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MainNewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    /**
     * app未打开，获取从推送过来的内容
     *
     * @param context
     * @param data
     */
    public static void startActivity(Context context, String data) {
        Intent intent = new Intent(context, MainNewActivity.class);
        intent.putExtra(KEY_CONTENT, data);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void onSingleClick(View v) {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main_new;
    }

    @Override
    protected MainNewPresenter getPresenter() {
        return new MainNewPresenter(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        KLog.i("========onNewIntent");
        setIntent(intent);
        disposeJPush();
        int action = intent.getIntExtra(AppStatusManager.KEY_HOME_ACTION, AppStatusManager.STATUS_NORMAL);
        switch (action) {
            case AppStatusManager.ACTION_RESTART_APP:
                protectApp();
                break;
            default:
                break;
        }
//        for (Fragment fragment : fragmentList) {
//            getSupportFragmentManager().beginTransaction().remove(fragment).commit();
//            KLog.i("=====移除fragment:" + fragment.getTag());
//        }
//        pagerAdapter = null;
//        HomeFragment.currentTabPosition = 1;
//        initViewPager();
    }

    @Override
    protected void initData() {
        super.initData();
        changeDecorView(4);
        RxBus2.get().register(this);
        updateApkStatus = -1;
        MobSDK.init(this);
        initUserInfo();
        checkPermissions();
        initViewPager();
        checkUpgrade();
        checkInitUrl();
        //启动websockets连接
        WebSocketServiceManager.getInstance(DCApplication.getDCApp()).startWebSocketService();

        disposeJPush();

        GlobalParams.StaticVariable.sCurrentNetwork = NetUtil.getNetworkState(MainNewActivity.this);
        KLog.i("=======sCurrentNetwork:" + GlobalParams.StaticVariable.sCurrentNetwork);
//        getWeakHandler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                GlobalParams.StaticVariable.sCurrentNetwork = NetUtil.getNetworkState(MainNewActivity.this);
//                if (GlobalParams.StaticVariable.sCurrentNetwork == 1 && !GlobalParams.StaticVariable.sHasShowdAllowdMobile) {
//                    showUseMobileNetwork();
//                    GlobalParams.StaticVariable.sHasShowdAllowdMobile = true;
//                }
//            }
//        }, 2000);
        jpushBindUserPresenter = new JpushBindUserPresenter(this);
        addPresenter(jpushBindUserPresenter);
        //循环获取JPush ID
        getWeakHandler().postDelayed(runnable, 2000);
    }

    //是否需要拉取url
    private void checkInitUrl() {
        if (GlobalParams.StaticVariable.sInitFromLocal) {
            presenter.init();
        }
    }

    //检查升级
    private void checkUpgrade() {
        if ("baidu".equals(DeviceUtils.getMetadata(DCApplication.getDCApp(), "UMENG_CHANNEL").toLowerCase())) {
            //百度升级
            AIUpdateSDK.updateCheck(MainNewActivity.this, checkUpdateCallback);
        } else {
            presenter.checkSystemAppUpdate(String.valueOf(GlobalParams.Config.APP_VERSION), DeviceUtils.getMetadata(DCApplication.getDCApp(), "UMENG_CHANNEL"));
        }
    }

    private void initViewPager() {
        vpContainer.setScrollable(true);
        fragmentList = new ArrayList<>();
        homeFragment = HomeFragment.newInstance();
        infoFragment = InfoFragment.newInstance(true);
        fragmentList.add(homeFragment);
        fragmentList.add(infoFragment);
        pagerAdapter = new MainNewViewPagerAdapter(getSupportFragmentManager(), fragmentList);
        vpContainer.setAdapter(pagerAdapter);
        vpContainer.addOnPageChangeListener(this);
        homeFragment.setUserInfoCallback(this);
    }

    //初始化个人信息
    private void initUserInfo() {
        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, Boolean>() {
                    @Override
                    public Boolean apply(Integer integer) throws Exception {
                        KLog.i("=====开始初始化本地账号信息");
                        AccountUtil.initUserInfo();
                        return true;
                    }
                })
                .observeOn(Schedulers.io())
                .subscribe();
    }

    private CheckUpdateCallback checkUpdateCallback = new CheckUpdateCallback() {
        @Override
        public void onCheckUpdateCallback(com.baidu.aiupdatesdk.UpdateInfo updateInfo) {
            if (null != updateInfo) {
                final BaiduUpdateDialog updateBaiduDialog = new BaiduUpdateDialog(MainNewActivity.this);
                if (updateInfo.isForceUpdate()) {
                    updateBaiduDialog.setBtnCancelVisibity(View.GONE);
                }
                updateBaiduDialog.setCancelable(!updateInfo.isForceUpdate());
                updateBaiduDialog.setContent(Html.fromHtml(updateInfo.getChangeLog()));
                updateBaiduDialog.setBtnOKText("智能升级");
                updateBaiduDialog.setBtnCancelText("暂不升级");
                updateBaiduDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                            return true;
                        }
                        return false;
                    }
                });
                updateBaiduDialog.setForceUpdate(updateInfo.isForceUpdate());
                updateBaiduDialog.setBaseDialogOnclicklistener(new BaseDialog.BaseDialogOnclicklistener() {

                    @Override
                    public void onOkClick(Dialog dialog) {
                        AIUpdateSDK.updateDownload(MainNewActivity.this);
                        updateBaiduDialog.dismiss();
                    }

                    @Override
                    public void onCancleClick(Dialog dialog) {
                        updateBaiduDialog.dismiss();
                    }
                });
                updateBaiduDialog.show();
            }
        }
    };

    //检查权限
    private void checkPermissions() {
        checkPermissionsStatus(permissionParams, new BaseCompatActivity.PermissionCallbackInterface() {
            @Override
            public void onPermissionsHasCallback() {
                //通知更新本地视频
                DiscoveryUtil.updateLocalVideo(DCApplication.getDCApp(), null);
                if (!DyUIAPI.isInitialized()) {
                    DCApplication appImp = (DCApplication) DCApplication.getDCApp();
                    appImp.initializeDyUIAPI();
                }
            }

            @Override
            public void onPermissionsGrantedCallback(int requestCode, List<String> params) {

            }

            @Override
            public void onPermissionsDeniedCallback(int requestCode, List<String> params) {
                if (params != null) {
                    for (String param : params) {
                        KLog.e("---------------------params-------------------------:" + params);
                    }
                }
                ToastUtil.showToast("请到系统设置里授权 动次 必要的权限，以免影响动次正常使用");
            }
        });
    }

    @Override
    public void checkSystemAppUpdateSucceed(final UpdateInfo updateInfo) {
        if (updateInfo != null && !TextUtils.isEmpty(updateInfo.getApp_url())) {
            mUpDateDialog = new UpDateDialog(MainNewActivity.this);
            mUpDateDialog.setTitle(updateInfo.getTips_title());
            if (updateInfo.isForce()) {
                mUpDateDialog.setBtnCancelVisibity(View.GONE);
            }
            mUpDateDialog.setContent(updateInfo.getTips_text());
            mUpDateDialog.setBtnOKText(getText(R.string.update_information_ok));
            mUpDateDialog.setCancelable(!updateInfo.isForce());
//            updateDialog.setButOKEnable(true);
            mUpDateDialog.setBaseDialogOnclicklistener(new BaseDialog.BaseDialogOnclicklistener() {

                @Override
                public void onOkClick(Dialog dialog) {
                    UpdateUtils.download(MainNewActivity.this, updateInfo.getApp_url(), updateInfo.getApp_name(), updateInfo.getFile_name());
                    if (!updateInfo.isForce()) {
                        mUpDateDialog.dismiss();
                    } else {
                        //强制升级
                        mUpDateDialog.setBtnOKText(getText(R.string.update_loading));
                    }
                }

                @Override
                public void onCancleClick(Dialog dialog) {
                    mUpDateDialog.dismiss();
                }
            });
            mUpDateDialog.show();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (currentPage == 1) {
                currentPage = 0;
                vpContainer.setCurrentItem(0, true);
                return true;
            }

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showToast("再按一次退出应用");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                DCApplication.getDCApp().exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * token失效重新登录的事件
     *
     * @param rxBusMessage
     */
    @RxBusSubscribe(code = GlobalParams.EventType.TYPE_RELOGIN, threadMode = ThreadMode.MAIN)
    public void onReLoginEvent(Boolean rxBusMessage) {
        Activity activity = DCApplication.getDCApp().getCurrentActivity();
        KLog.i("======收到消息：" + rxBusMessage + "_" + activity);
        //清除账号信息
        AccountUtil.clearAccount();
        if (null != activity && (activity instanceof DcBaseActivity || activity instanceof BaseCompatActivity)) {
            if (activity instanceof PersonalHomeActivity || activity instanceof FocusActivity || activity instanceof FansActivity) {

            } else {
                ((BaseCompatActivity) activity).showReLogin();
            }
        }
    }

    //网络变化的事件result为0时正常，1是移动网络，2是无网络
    @RxBusSubscribe(code = GlobalParams.EventType.TYPE_NETWORK_CHANGE, threadMode = ThreadMode.MAIN)
    public void onNetworkChange(Integer result) {
        KLog.i("======网络发生变化：" + result);
        Activity activity = DCApplication.getDCApp().getCurrentActivity();
//        if (result == 1 && !GlobalParams.StaticVariable.sHasShowdAllowdMobile) {//只有再次切换到wifi网络后才重置
//            if (null != activity && (activity instanceof DcBaseActivity || activity instanceof BaseCompatActivity)) {
//                if (activity instanceof MainNewActivity) {//只有这两个页面需要弹窗
//                    ((MainNewActivity) activity).showUseMobileNetwork();
//                } else if (activity instanceof VideoListActivity) {
//                    ((VideoListActivity) activity).showUseMobileNetwork();
//                }
//            }
//            GlobalParams.StaticVariable.sHasShowdAllowdMobile = true;
//        }
        if (result == 0) {//切换到wifi网络后
            GlobalParams.StaticVariable.sHasShowdAllowdMobile = false;
            // 如果之前没有播放，则开始播放
            if (!DcIjkPlayerManager.get().isPlaying()) {
                if (null != activity && (activity instanceof DcBaseActivity || activity instanceof BaseCompatActivity)) {
                    if (activity instanceof MainNewActivity) {//只有这两个页面需要弹窗
                        if (HomeFragment.currentTabPosition == 0
                                || HomeFragment.currentTabPosition == 1) {
                            homeFragment.resumePlay();
                        }
                    } else if (activity instanceof VideoListActivity) {
                        ((VideoListActivity) activity).resumePlay();
                    }
                }
            }
        }
    }

    //显示是否使用移动网络播放视频
    public void showUseMobileNetwork() {
        if (useMobileDialog == null) {
            useMobileDialog = new MyDialog("", getString(R.string.stringMobileNetworkHint), "是", "否", false, new MyDialogClickListener() {
                @Override
                public void onPositiveClick(DialogInterface dialog, int which) {
                    super.onPositiveClick(dialog, which);
                    GlobalParams.StaticVariable.sAllowdMobile = true;
                }

                @Override
                public void onNegativeClick(DialogInterface dialog, int which) {
                    super.onNegativeClick(dialog, which);
                    GlobalParams.StaticVariable.sAllowdMobile = false;
                }
            });
        }
        if (!useMobileDialog.isShowing()) {
            useMobileDialog.show(this);
        }
    }

    //控制ViewPager的滑动
    @RxBusSubscribe(code = GlobalParams.EventType.TYPE_SCROLL, threadMode = ThreadMode.MAIN)
    public void onScrollEvent(Boolean canScroll) {
        KLog.i("======收到是否可滑动消息：" + canScroll);
        vpContainer.setScrollable(canScroll);
    }

    @Override
    protected void onResume() {
        //检测未编辑完成的视频信息
        DyUIAPIManager.getInstance().onCheckUnFinishData(MainNewActivity.this);
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        RxBus2.get().unRegister(this);
        stopService(new Intent(this, DCService.class));
        super.onDestroy();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if (position == 0) {
            DeviceUtils.setWindowStatusBarColor(this, R.color.transparent);
        } else {
            DeviceUtils.setWindowStatusBarColor(this, R.color.app_background_color);
        }
    }

    @Override
    public void onPageSelected(int position) {
        currentPage = position;
    }

    @Override
    public void getUserInfo(long userId) {
        if (userId > 0 && infoFragment != null) {
            infoFragment.getUserInfo(userId);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void checkSystemAppUpdateFailure(String updateInfo) {

    }

    @Override
    public void initApiError(String msg) {

    }

    @Override
    public void initApiSucceed() {

    }

    @Override
    public void onInitComplete() {

    }

    /**
     * 处理推送过来的消息，跳转到各个业务
     */
    public static final String KEY_CONTENT = "jpush_content";//从jpush广播传过来的内容

    private void disposeJPush() {
        try {
            String data = getIntent().getStringExtra(KEY_CONTENT);
            Navigator.getInstance().bannerLink(this, data);
        } catch (Exception e) {

        }
    }

    /**
     * 极光 绑定用户ID
     */
    private void bindUser() {
        KLog.i("MainNewActivity", ">>>>deveice id >>>" + DeviceUtils.getDeviceId());
        String regId = JPushInterface.getRegistrationID(this.getApplicationContext());
        if (null != jpushBindUserPresenter && !TextUtils.isEmpty(regId)) {
            getWeakHandler().removeCallbacks(runnable);
            jpushBindUserPresenter.bindUser(DeviceUtils.getDeviceId(), regId);
        }
    }

    @Override
    protected void protectApp() {
        KLog.i("应用被回收重启走流程");
        startActivity(new Intent(this, SplashActivity.class));
        finish();
    }

    @Override
    public void handleBindSucceed() {
        KLog.i("JpushReceiver", ">>>>bind user success>>>");
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            bindUser();
        }
    };
}
